#include "maincontrol.h"

MainControl::MainControl(SettingsData settingsData, QObject *parent) : QObject(parent),
    m_settingsData(settingsData)
{
    m_settingsData = settingsData;
    m_validNum = 0;
}

MainControl::~MainControl()
{
    stopThread();
}

//step 2
void MainControl::initThread()
{
    for(int i = 0; i < m_validNum; i++) {
        QThread *m_thread = new QThread;
        SaveFileThread *m_savefileThread = new SaveFileThread();
        m_savefileThread->moveToThread(m_thread);
        m_savefileThread->setInfo(m_videoConfigs[i].ip, m_videoConfigs[i].resourcesName,
                                  m_videoConfigs[i].port, m_settingsData.fileSavePath);  // 参数：[目标IP] [保存的文件夹的名和dat文件的前缀描述]
        m_savefileThread->setParam(m_settingsData);
        m_thread->start();
        m_threads.push_back(m_thread);
        connect(this, &MainControl::signal_saveFileWork, m_savefileThread, &SaveFileThread::working);
    }
}

//step 3
void MainControl::startThread()
{
    for(auto thread : m_threads) {
        thread->start();
    }
}

//step 4
void MainControl::stopThread()
{
    for(auto thread : m_threads) {
        if(thread) {
            thread->quit();
            thread->wait();
            thread->deleteLater();
            thread = nullptr;
        }
    }
}

//step 1
void MainControl::setConfig(const QVector<WINDOW_CONFIG> &configs, int validNum)
{
    m_videoConfigs = configs;
    m_validNum = validNum;
}

//step 1
void MainControl::onSettingsData(const SettingsData &settingsData)
{
    qDebug() << "收到的配置是:";
    qDebug() << settingsData.deleteWayIndex;
    qDebug() << settingsData.saveMaxNum;
    qDebug() << settingsData.mSize;
    qDebug() << settingsData.fileSavePath;

    m_settingsData.mSize = settingsData.mSize;
    m_settingsData.saveMaxNum = settingsData.saveMaxNum;
    m_settingsData.deleteWayIndex = settingsData.deleteWayIndex;
    m_settingsData.fileSavePath = settingsData.fileSavePath;

    stopThread();
    m_threads.clear();

    initThread();
    startThread();
}
